/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-04-26
 * Time:20:22
 */

/**
 * Jz27 二叉树的镜像
 */
import java.util.Stack;
public class Mirror {
    public TreeNode Mirror (TreeNode root) {
        //递归
//        if (root == null) {
//            return null;
//        }
//        TreeNode tmp = root.left;
//        root.left = Mirror(root.right);
//        root.right = Mirror(tmp);
//        return root;
        //迭代
        if (root == null) {
            return null;
        }

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();

            // 交换左右子节点
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;

            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
        }
        return root;
    }
}
